package com.jvmoutofmemory.platform.pushutil.service;

import com.alibaba.fastjson2.JSON;
import com.jvmoutofmemory.platform.pushutil.constants.PushJobStatus;
import com.jvmoutofmemory.platform.pushutil.dao.PushJobDao;
import com.jvmoutofmemory.platform.pushutil.dto.PushResult;
import com.jvmoutofmemory.platform.pushutil.entity.PushJob;
import com.jvmoutofmemory.platform.pushutil.response.PushResponseListener;
import com.jvmoutofmemory.platform.pushutil.response.PushResponseParser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用于统一执行推送请求
 * Created by Administrator on 2017/6/8 0008.
 */
public class PushJobService implements PushService {
    private static final Logger logger = LoggerFactory.getLogger(PushJobService.class);

    @Autowired
    private PushJobDao pushJobDao;
    @Autowired
    private PushComponent pushComponent;

    private ExecutorService executorService = Executors.newFixedThreadPool(2);

    @Override
    @Transactional
    public int deleteById(Long id) {
        return pushJobDao.deleteById(id);
    }

    /**
     * 查询N天前的，推送成功的数据
     * @param days
     * @return
     */
    @Override
    public List<Long> selectFinishData(int days) {
        return pushJobDao.selectFinishData(days);
    }

    /**
     * 获取所有未推送的请求
     */
    @Override
    public List<PushJob> selectNotPushedPushJobList(int size) {
        return pushJobDao.selectNotPushed(size);
    }

    /**
     * 获取所有推送失败但未到达最大失败次数的请求
     */
    @Override
    public List<PushJob> selectFailedPushJobList(int size) {
        return pushJobDao.selectPushFailed(size);
    }

    /**
     * 执行推送
     */
    @Override
    @Transactional
    @SuppressWarnings({"rawtypes"})
    public void push(PushJob pushJob) throws Exception {
        PushResult pushResult = pushComponent.push(pushJob);
        pushJob.setTimes(pushJob.getTimes() + 1);

        PushResponseListener listener = pushComponent.getPushResponseListener(pushJob);
        if (pushResult.isSuccess()) {
            onSendSuccess(listener, pushJob, pushResult);
        } else {
            onSendFailure(listener, pushJob, pushResult);
        }

        if (pushJob.getId() != null) {
            pushJob.setParam(null);//不更新clob/text字段
            pushJobDao.updateByIdNonNull(pushJob);
        }

        logger.info("推送任务执行完成! {}", String.format("%s   %s", pushJob.getRequestId(), pushJob.getUrl()));
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private void onSendSuccess(PushResponseListener listener, PushJob pushJob, PushResult result) {
        pushJob.setMsg(result.getBody());
        pushJob.setStatus(PushJobStatus.SUCCESS.getCode());

        if (listener != null) {
            pushJob.setCallbackTimes(pushJob.getCallbackTimes() == null ? 1 : pushJob.getCallbackTimes() + 1);
            try {
                Class c = Object.class;
                if (!StringUtils.isEmpty(pushJob.getCallBackType())) {
                    c = Class.forName(pushJob.getCallBackType());
                }
                listener.onSuccess(JSON.parseObject(pushJob.getCallBackParam(),c), result.getBody());
                pushJob.setCallbackStatus(PushJob.CALLBACK_SUCCESS);
            } catch (Exception e) {
                pushJob.setCallbackStatus(PushJob.CALLBACK_FAILED);
                logger.error("调用listener失败! {}", listener);
                logger.error(e.getMessage(), e);
            }
        }
//            pushJobDao.deleteById(pushJob.getId());//推送成功后直接删除
    }

    @SuppressWarnings({"rawtypes"})
    private void onSendFailure(PushResponseListener listener, PushJob pushJob, PushResult result) {
        pushJob.setMsg(result.getMsg());
        pushJob.setStatus(PushJobStatus.FAILED.getCode());
        if (listener != null) {
            pushJob.setCallbackTimes(pushJob.getCallbackTimes() == null ? 1 : pushJob.getCallbackTimes() + 1);
            try {
                Class c = Object.class;
                if (!StringUtils.isEmpty(pushJob.getCallBackType())) {
                    c = Class.forName(pushJob.getCallBackType());
                }
                listener.onFailure(JSON.parseObject(pushJob.getCallBackParam(), c), result.getBody());
                pushJob.setCallbackStatus(PushJob.CALLBACK_SUCCESS);
            } catch (Exception e) {
                pushJob.setCallbackStatus(PushJob.CALLBACK_FAILED);
                logger.error("listener失败! {}", listener);
                logger.error(e.getMessage(), e);
            }
        }
    }

    @Override
    @Transactional
    public void insertOne(PushJob pushJob) {
        pushJobDao.insert(pushJob);
    }

    @Override
    public void pushNow(PushJob pushJob) throws Exception {
        this.push(pushJob);
    }

    @Override
    public void pushNowQuietly(PushJob pushJob) {
        try {
            this.pushNow(pushJob);
        } catch (Exception exception) {
            logger.error(exception.getMessage(), exception);
        }
    }

    @Override
    @Transactional
    @SuppressWarnings({"rawtypes"})
    public void pushOrSave(PushJob pushJob) {
        PushResult pushResult = pushComponent.push(pushJob);
        pushJob.setTimes(pushJob.getTimes() + 1);

        PushResponseListener listener = pushComponent.getPushResponseListener(pushJob);
        if (pushResult.isSuccess()) {
            onSendSuccess(listener, pushJob, pushResult);
        } else {
            onSendFailure(listener, pushJob, pushResult);
            this.insertOne(pushJob);
        }

        logger.info("推送任务执行完成! {}", String.format("%s   %s", pushJob.getRequestId(), pushJob.getUrl()));
    }

    @Override
    public PushResponseParser getResponseParser(String type) {
        return pushComponent.getResponseParser(type);
    }
}

